package health

import (
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/config"
	"techoiceness.com/aiagent/llm-gateway/internal/database"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// HealthHandler 健康检查处理器
type HealthHandler struct {
	cfg *config.Config
	db  *gorm.DB
}

// NewHealthHandler 创建健康检查处理器
func NewHealthHandler(cfg *config.Config, db *gorm.DB) *HealthHandler {
	return &HealthHandler{
		cfg: cfg,
		db:  db,
	}
}

// Health 基础健康检查
func (h *HealthHandler) Health(c echo.Context) error {
	if err := database.HealthCheck(h.db); err != nil {
		resp := HealthResponse{
			Status: "unhealthy",
			Error:  err.Error(),
		}
		return c.JSON(http.StatusServiceUnavailable, resp)
	}

	resp := HealthResponse{
		Status: "healthy",
	}
	return c.JSON(http.StatusOK, resp)
}

// HealthDetailed 详细健康检查
func (h *HealthHandler) HealthDetailed(c echo.Context) error {
	result, err := database.HealthCheckDetailed(h.db)
	if err != nil {
		return response.InternalServerError(c, "health check failed: "+err.Error())
	}

	switch result.Status {
	case "unhealthy":
		return c.JSON(http.StatusServiceUnavailable, result)
	case "degraded":
		return c.JSON(http.StatusAccepted, result)
	default:
		return response.Success(c, result)
	}
}

// DatabaseMetrics 数据库指标
func (h *HealthHandler) DatabaseMetrics(c echo.Context) error {
	metrics, err := database.GetDatabaseMetrics(h.db)
	if err != nil {
		return response.InternalServerError(c, "failed to get database metrics: "+err.Error())
	}

	return response.Success(c, metrics)
}

// DatabaseStats 数据库统计信息
func (h *HealthHandler) DatabaseStats(c echo.Context) error {
	stats, err := database.GetConnectionStats(h.db)
	if err != nil {
		return response.InternalServerError(c, "failed to get database stats: "+err.Error())
	}

	return response.Success(c, stats)
}

// TableSizes 表大小信息
func (h *HealthHandler) TableSizes(c echo.Context) error {
	sizes, err := database.GetTableSizes(h.db)
	if err != nil {
		return response.InternalServerError(c, "failed to get table sizes: "+err.Error())
	}

	// 转换为DTO格式
	tables := make([]TableSizeInfo, 0, len(sizes))

	for _, size := range sizes {
		table := TableSizeInfo{
			TableName: size.TableName,
			RowCount:  size.SizeBytes, // 使用SizeBytes作为大小指标
			DataSize:  size.Size,
			IndexSize: "", // 数据库返回的结构没有单独的索引大小
			TotalSize: size.Size,
		}
		tables = append(tables, table)
	}

	resp := TableSizesResponse{
		Tables:    tables,
		TotalSize: "", // 可以在这里计算总大小
		Timestamp: time.Now(),
	}

	return response.Success(c, resp)
}

// RegisterRoutes 注册健康检查路由
func (h *HealthHandler) RegisterRoutes(e *echo.Echo) {
	e.GET("/health", h.Health)
	e.GET("/health/detailed", h.HealthDetailed)
	e.GET("/metrics/database", h.DatabaseMetrics)
	e.GET("/metrics/database/stats", h.DatabaseStats)
	e.GET("/metrics/database/tables", h.TableSizes)
}
